package com.fast.linkbeanadmin.security.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fast.linkbeanadmin.constants.CacheConstants;
import com.fast.linkbeanadmin.pojo.dto.SecurityUserDTO;
import com.fast.linkbeanadmin.pojo.dto.TokenDTO;
import com.fast.linkbeanadmin.utils.jwt.JwtUtil;
import com.fast.linkbeanadmin.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.linkbeanadmin.security.filter.TokenAuthenticationFilter
 * @description: token认证过滤器, 作用:把用户信息填充进SecurityContext。因为: AnonymousAuthenticationFilter会判断SecurityContextHolder.getContext().getAuthentication() == null,
 * 如果成立则创建一个匿名的Authentication,导致在FilterSecurityInterceptor中抛出AccessDeniedException, 再被ExceptionTranslationFilter捕获该异常后回调authenticationEntryPoint.commence()导致登录后仍提示需要登录
 * @since 2024/8/28 10:00
 */
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private final RedisUtil redisUtil;

    public TokenAuthenticationFilter(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("request uri:{}", request.getRequestURI());

        //请求头中含有：Authorization，可自定义约定
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (token == null) {
            // 把授权的控制交给FilterSecurityInterceptor
            filterChain.doFilter(request, response);
            return;
        }

        DecodedJWT decodedJWT = JwtUtil.verify(token);

        // 解析获取token包含 的用户信息
        TokenDTO tokenDTO = JwtUtil.parse(decodedJWT, TokenDTO.class);

        if (tokenDTO == null) {
            filterChain.doFilter(request, response);
            return;
        }

        SecurityContextHolder.getContext().setAuthentication(buildAuthentication(tokenDTO));
        filterChain.doFilter(request, response);
    }

    private Authentication buildAuthentication(TokenDTO tokenDTO) {
        // 登录成功后已把用户信息放入缓存,此时直接取出
        SecurityUserDTO securityUserDto = redisUtil.get(CacheConstants.LOGIN_USERNAME_KEY + tokenDTO.getUsername(), SecurityUserDTO.class);
        if (securityUserDto == null) {
            return null;
        }
        Collection<? extends GrantedAuthority> authorities = securityUserDto.getAuthorities();
        return new UsernamePasswordAuthenticationToken(securityUserDto, null, authorities);
    }
}
